package com.lw.leetcode.arr.b;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 2257. 统计网格图中没有被保卫的格子数
 *
 * @author liw
 * @version 1.0
 * @date 2022/5/4 20:13
 */
public class CountUnguarded {

    public static void main(String[] args) {
        CountUnguarded test = new CountUnguarded();

        // 3
        int m = 5;
        int n = 5;
        int[][] arr1 = {{1, 4}, {4, 1}, {0, 3}};
        int[][] arr2 = {{3, 2}};
        int i = test.countUnguarded(m, n, arr1, arr2);

        System.out.println(i);
    }


    private Map<Long, Integer> map = new HashMap<>();

    public int countUnguarded(int m, int n, int[][] guards, int[][] walls) {
        int[][] arr = new int[m][n];
        for (int[] wall : walls) {
            arr[wall[0]][wall[1]] = 1;
        }
        for (int[] guard : guards) {
            arr[guard[0]][guard[1]] = 3;
        }
        for (int[] guard : guards) {
            find(arr, guard[0], guard[1]);
        }
        int count = 0;
        for (int[] ints : arr) {
            for (int anInt : ints) {
                if (anInt == 0) {
                    count++;
                }
            }
        }
        return count;
    }

    private void find(int[][] arr, int x, int y) {
        int m = arr.length;
        int n = arr[0].length;

        long key = ((long) x << 32) + y;
        Integer value = map.get(key);
        if (value == null || value != 1) {
            for (int i = y - 1; i >= 0; i--) {
                if (arr[x][i] == 1 || arr[x][i] == 3) {
                    break;
                }
                arr[x][i] = 2;
            }
        }
        for (int i = y + 1; i < n; i++) {
            if (arr[x][i] == 1) {
                break;
            }
            if (arr[x][i] == 3) {
                map.put(((long) x << 32) + i, 1);
                break;
            }
            arr[x][i] = 2;
        }
        if (value == null || value != 2) {
            for (int i = x - 1; i >= 0; i--) {
                if (arr[i][y] == 3 || arr[i][y] == 1) {
                    break;
                }
                arr[i][y] = 2;
            }
        }
        for (int i = x + 1; i < m; i++) {
            if (arr[i][y] == 1) {
                break;
            }
            if (arr[i][y] == 3) {
                map.put(((long) i << 32) + y, 2);
                break;
            }
            arr[i][y] = 2;
        }
    }

}
